package com.summer.core.container;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;

import com.taobao.api.domain.User;

/**
 * @author dlc
 * @CreateDate 2007-4-4
 * TODO 
 */
public class OnlineAppMap {

    private static Map cache = null;
    
    static {
        if(cache == null)
            cache = new Hashtable();
    }
    
    public static final Map getAppMap() {
        return cache;
    }
    
    /**
     * 用户登陆
     * @param sessionId
     * @param session
     */
    public final static void put(String sessionId,HttpSession session) {
        cache.put(sessionId,session);
    }
    
    /**
     * 强制指定session下线
     * @param sessionId
     */
    public final static void ban(String sessionId) {
        HttpSession session = (HttpSession) cache.get(sessionId);
        if(session != null) {
           // User userInfo = SessionContainerUtil.getUser(session);
           // LoginLogHome.logLogout(userInfo,sessionId,"管理员强制退出系统");
            cache.remove( sessionId );
            session.removeAttribute(Const.SessionContainer);	//在sesion.invalidate()之前将userInfo从session中清除
            session.invalidate();
        }
    }
    
    /**
     * 强制当前所有用户下线
     * @return
     */
    public final static int banAll() {
        int count = 0;
        Set keySet = cache.keySet();
        Iterator i = keySet.iterator();
        while(i.hasNext()) {
            String key = (String) i.next();
            HttpSession session = (HttpSession) cache.get(key);
            User userInfo = SessionContainerUtil.getUser(session);
            //LoginLogHome.logLogout(userInfo,session.getId(),"管理员强制退出系统");
            
            i.remove();
            session.removeAttribute(Const.SessionContainer);
            session.invalidate();
            count++;
        }
        return count;
    }
    
    public final static boolean checkOnline(String user_id) {
        boolean online = false;
        Set keySet = cache.keySet();
        Iterator i = keySet.iterator();
        while(i.hasNext()) {
            String key = (String) i.next();
            HttpSession session = (HttpSession) cache.get(key);
            User userInfo = SessionContainerUtil.getUser(session);
            if (userInfo!=null && userInfo.getUserId().equals(user_id)) {
                online = true;
                break;
            }
        }
        return online;
    }
}
